package com.example.yzx.allriddle;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import com.example.yzx.allriddle.daomain.QApp;
import com.example.yzx.allriddle.utils.Db;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

public class ReadActivity extends AppCompatActivity {
    private TextView context;
    static int pid=1;
    static String style="xiaohua/text";
    private Spinner spinner;
    private Db db = new Db(this, 1);
    private QApp app;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read);
        //收藏引导
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null){
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        context=findViewById(R.id.ct);
        spinner=findViewById(R.id.Spinner);
        app= (QApp) getApplication();
        SQLiteDatabase sqLiteDb = db.getWritableDatabase();
        String sql2="CREATE TABLE  IF NOT EXISTS star(id integer primary key autoincrement,uid integer,starid integer, type varchar(60),FOREIGN KEY(uid)REFERENCES user(uid))";
        sqLiteDb.execSQL(sql2);
        sqLiteDb.close();
        sendRequestWithOkHttp(pid,style);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
            {
                if(position==0){
                    style="xiaohua/text";
                }else if(position==1){
                    style="miyu/search";
                }else if(position==2){
                    style="jzw/search";
                }
                sendRequestWithOkHttp(pid,style);
            } // to close the onItemSelected
            public void onNothingSelected(AdapterView<?> parent)
            {
                System.out.println("没有改变");
            }
        });
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish(); // back button
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
    //star
    public void star(View view){
        System.out.println("插入数据");
        SQLiteDatabase sqLiteDb = db.getWritableDatabase();
        sqLiteDb = db.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("uid",app.getserid());
        cv.put("starid",pid);
        cv.put("type",style);
        sqLiteDb.insert("star", null, cv);
        sqLiteDb.close();
        AlertDialog alertDialog2 = new AlertDialog.Builder(this)
                .setTitle("收藏成功")//标题
                .setMessage(" ")//内容
                .create();
        alertDialog2.show();
        SQLiteDatabase  sqLiteDbup = db.getReadableDatabase();
        Cursor c = sqLiteDbup.query("star", new String[]{"id", "type", "uid","starid"}, null, null, null, null, null);
        boolean sign=true;
        while (c.moveToNext()) {
            Integer id = c.getInt(c.getColumnIndex("id"));
            String name = c.getString(c.getColumnIndex("uid"));
            String names = c.getString(c.getColumnIndex("starid"));
            String word = c.getString(c.getColumnIndex("type"));
            System.out.println(id+name+word+names);
        }
    }

    //下一个
    public void nexts(View view){
        sendRequestWithOkHttp(pid++,style);
    }

    //上一个
    public void lasts(View view){
        if(pid>1)
            sendRequestWithOkHttp(pid--,style);
        else{
            AlertDialog alertDialog2 = new AlertDialog.Builder(this)
                    .setTitle("到底了")//标题
                    .setMessage(" ")//内容
                    .create();
            alertDialog2.show();
        }
    }

    //选择器
    public void select(View view){
        System.out.println("?//");
    }
    private Handler hand = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                String title = (String) msg.obj;
                context.setText(title);
            }
        }

    };

    private void sendRequestWithOkHttp(final int pageid,final String type) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client=new OkHttpClient();
                    String url="";
                    if(type.equals("xiaohua/text"))
                        url="https://api.jisuapi.com/"+type+"?pagenum="+pageid+"&pagesize=1&sort=addtime&appkey=85cdfb160033ed3f";
                    else if(type.equals("miyu/search"))
                        url="https://api.jisuapi.com/"+type+"?pagenum="+pageid+"&pagesize=1&appkey=85cdfb160033ed3f";
                    else if(type.equals("jzw/search"))
                        url="https://api.jisuapi.com/"+type+"?keyword=&pagenum="+pageid+"&pagesize=1&appkey=85cdfb160033ed3f";
                    Request request=new Request.Builder()
                        .url(url)
                        .build();
                    Response response=client.newCall(request).execute();
                    String data=response.body().string();
                    json(data);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void json(String data){
        try {
            JSONObject json = new JSONObject(data);
            JSONObject result = json.getJSONObject("result");
            String pid="";
            if(!style.equals("miyu/search"))
                 pid=result.getString("pagenum");
            JSONArray results = result.getJSONArray("list");
            JSONObject obj=results.getJSONObject(0);
            String content=obj.getString("content");
            if(!style.equals("xiaohua/text")){
                content+="\n\n         谜底 ："+obj.getString("answer");
            }
            //传送
            Message message = hand.obtainMessage();
            message.what = 1;
            message.obj = content;
            hand.sendMessage(message);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
